//Given n pairs of parentheses, write a function to generate all combinations of
// well-formed parentheses. 
//
// 
// Example 1: 
// Input: n = 3
//Output: ["((()))","(()())","(())()","()(())","()()()"]
// Example 2: 
// Input: n = 1
//Output: ["()"]
// 
// 
// Constraints: 
//
// 
// 1 <= n <= 8 
// 
// Related Topics 字符串 回溯算法 
// 👍 1781 👎 0


package leetcode.editor.cn;

import java.util.ArrayList;
import java.util.List;

//Java：Generate Parentheses
class P22GenerateParentheses {
    public static void main(String[] args) {
        Solution solution = new P22GenerateParentheses().new Solution();
        // TO TEST
        System.out.println(solution.generateParenthesis(3));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public List<String> generateParenthesis(int n) {
            List<String> result = new ArrayList<>();
            generateParenthesis(new String(), n, 0, 0, result);
            return result;
        }

        private void generateParenthesis(String s, int n, int left, int right, List<String> result) {
            if (left > n || right > n) {

                return;
            }
            if (left == right && left == n) {
                result.add(s);
                return;
            }
            if (right > left) {
                return;
            }
            generateParenthesis(s + "(", n, left + 1, right, result);
            generateParenthesis(s + ")", n, left, right + 1, result);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}